package ding

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"runtime"
	"strings"
)

//只有自己的
const testUrl = "https://oapi.dingtalk.com/robot/send?access_token=2cac4735e33c34bc1f42ca9ea73b328cbb78d349171d4dee5f12fbf372889d0b"

// 报错提醒
func DingErr(str string) {
	if _, file, line, ok := runtime.Caller(1); ok {
		str = fmt.Sprintf("\n 文件:%v,\n行号:%v,\n问题:%v", file, line, str)
	}
	httpPost(testUrl, "报错报警: "+str, []string{})
}

//自定义提醒
func DingGive(str string, mobile []string) {
	if _, file, line, ok := runtime.Caller(1); ok {
		str = fmt.Sprintf("\n 文件:%v,\n行号:%v,\n问题:%v", file, line, str)
	}
	httpPost(testUrl, "调试报警: "+str, mobile)
}

func httpPost(url, str string, mobile []string) string {
	str = "程序" + str
	//组装数据
	strMap := make(map[string]interface{})
	strMap["at"] = map[string]interface{}{
		"atMobiles": mobile,
	}
	strMap["msgtype"] = "text"
	strMap["text"] = map[string]string{
		"content": str,
	}
	strJson, err := json.Marshal(strMap)
	if err != nil {
		return err.Error()
	}

	resp, err := http.Post(url,
		"application/json;charset=utf-8",
		strings.NewReader(string(strJson)))
	if err != nil {
		return err.Error()
	}

	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	return string(body)
}
